package mysql

import (
	"pharymacy-management-system/models"
	"pharymacy-management-system/pkg/snowflake"
)

func SelectAllVip() (vipList []models.Vip, err error) {
	sqlStr := `select a.vip_id,a.user_id,a.integral,b.user_nick_name from w_vip a,w_user b where a.user_id=b.user_id and b.is_delete=1`
	rows, err := db.Queryx(sqlStr)
	if err != nil {
		return
	}
	defer rows.Close()

	for rows.Next() {
		var vip models.Vip
		err := rows.Scan(&vip.VipID, &vip.UserID, &vip.Integral, &vip.UserNickName)
		if err != nil {
			return nil, err
		}
		vipList = append(vipList, vip)
	}

	return
}

func CreateVip(vip *models.Vip) error {
	sqlStr := `insert into w_vip(vip_id,user_id,integral) values(?,?,?)`
	_, err := db.Exec(sqlStr, vip.VipID, vip.UserID, vip.Integral)
	return err
}

func SelectByUserID(userID int64) (*models.Vip, error) {
	var count int
	sqlStr := `select count(*) from w_vip where user_id=?`
	err := db.Get(&count, sqlStr, userID)
	if err != nil {
		return nil, err
	}
	if count == 0 {
		return nil, nil
	}
	var vip models.Vip
	sqlStr = `select vip_id,user_id,integral from w_vip  where user_id=?`
	err = db.Get(&vip, sqlStr, userID)
	return &vip, err
}

func UpdateVip(userID int64, number int, description string) error {
	historyID := snowflake.GenID()
	vip, err := SelectByUserID(userID)
	if err != nil {
		return err
	}
	var status int
	if vip.Integral > number {
		status = 0
	} else {
		status = 1
	}
	tx, err := db.Beginx()
	if err != nil {
		return err
	}
	sqlStr1 := `update w_vip set integral=? where user_id=?`
	sqlStr2 := `insert into w_vip_integral_history(history_id, vip_id, number, status, description) VALUES (?,?,?,?,?)`
	tx.MustExec(sqlStr1, number, userID)
	tx.MustExec(sqlStr2, historyID, vip.VipID, number, status, description)
	return tx.Commit()
}

func GetVipHistoryListByVipID(vipID int64) (historyList []models.VipHistory, err error) {
	sqlStr := `select a.history_id, a.vip_id, number, a.update_time, status, description,c.user_nick_name as user_name from w_vip_integral_history a,w_vip b,w_user c where a.vip_id=b.vip_id and b.user_id=c.user_id and a.vip_id=?`
	err = db.Select(&historyList, sqlStr, vipID)
	return
}
